﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace shenghua.Common.CustomValueType
{
    [Owned]
    public class ValueArray<T>
    {
        private List<T> _items;
        private string _value = "";

        public string StringValue
        {
            get
            {
                return _value;
            }
            set
            {
                _value = value;
                _items = null;
            }
        }

        [NotMapped]
        public List<T> Items
        {
            get
            {
                if (_items == null)
                {
                    if(string.IsNullOrWhiteSpace(_value))
                    {
                        _items = new List<T>();
                    }
                    else
                    {
                        _items = _value.Split(',').Select<string, T>(r => Parse(r)).ToList();
                    }
                }
                return _items;
            }
            set
            {
                if(value == null)
                {
                    StringValue = "";
                }
                else
                {
                    StringValue = string.Join(",", value);
                }
            }
        }

        public ValueArray()
        {

        }

        public ValueArray(string stringValue)
        {
            StringValue = stringValue;
        }

        public ValueArray(List<T> items)
        {
            Items = items;
        }

        private T Parse(string value)
        {
            Object result = null;
            Type TType = typeof(T);

            if (TType == typeof(string))
            {
                result = value;
            }
            else if (TType == typeof(int))
            {
                result = int.Parse(value);
            }
            else if (TType == typeof(long))
            {
                result = long.Parse(value);
            }

            return (T)result;
        }
    }
}
